package Shopping;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

public class Shopcart {
	private Goods goods;
	private double sum;
	static HashMap<String, Integer> hm = new HashMap<String, Integer>();

	public double getSum() {
		return sum;
	}

	public void setSum(double sum) {
		this.sum = sum;
	}

	public Goods getGoods() {
		return goods;
	}

	public void setGoods(Goods goods) {
		this.goods = goods;
	}

	public void Addgoods(String goodsname, Integer goodscount) {
		hm.put(goodsname, goodscount);
	}

	public void Delgoods(String goodsname) {
		hm.remove(goodsname);
	}

	public void ClearGoods() {
		hm.clear();
	}

	public void upGoods(String goodsname, Integer newNumber) {
		hm.put(goodsname, newNumber);
	}

	public Integer getGoodsNumberByGoodsName(String goodsname) {
		return hm.get(goodsname);
	}

	private static PreparedStatement ps = null;

	private static ResultSet rs = null;

	public  ArrayList<Goods> getAllGoods() {
		ArrayList<Goods> alist = new ArrayList<Goods>();
		try (Connection ct = new Connect().getConn();) {

			String sql = "select * from goodsbean where name in (";
			Iterator<String> it = hm.keySet().iterator();
			while (it.hasNext()) {
				String goodsname = it.next();
				if (it.hasNext()) {
					sql +="'"+ goodsname + "',";
				} else {
					sql += "'"+goodsname + "')";
				}
			}
			ps = ct.prepareStatement(sql);
			rs = ps.executeQuery();
			while (rs.next()) {
				alist.add(new Goods(rs.getInt("id"), rs.getString("name"), Double.parseDouble(rs.getString("price"))));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return alist;
	}

	public double toBalance() {
		double sum = 0;
		List<Goods> goodslist = getAllGoods();
		for (int i = 0; i < hm.size(); i++)
			sum += goodslist.get(i).getPrice() * hm.get(i).intValue();
		return sum;
	}

	public void displayAll() {
		if (hm.isEmpty())
			System.out.println("无任何商品");
		else {
			List<Goods> goodslist=getAllGoods();
			for (int i = 0; i < hm.size(); i++) {
				System.out.println(goodslist.get(i).getId() + "\t" + goodslist.get(i).getName() + "\t"
						+ goodslist.get(i).getPrice() + "\t" + hm.get(goodslist.get(i).getName()));
			}
		}
	}
}
